﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Automation;
using OpenCvSharp;

namespace YTSK.cSK.BWNew
{
    public class cKP_PP
    {
        #region dll

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(IntPtr hWnd, ref cDll.RECT lpRect);

        #endregion

        public static string proc(string filePath, out string fpdm, out string fphm)
        {
            var err = "";
            fpdm = "";
            fphm = "";
            IntPtr hWnd = cDll.FindWindow(null, "新开票软件"); //获取新开票句柄
            if (hWnd.ToInt32() == 0)
            {
                err = $"没有找到[新开票软件]窗口或者系统运行速度太慢，请与系统管理员联系";
                return err;
            }

            cDll.SetForegroundWindow(hWnd); //设置为活动窗口
            cDll.ShowWindow(hWnd, 1);
            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt() * 3);

            #region 对指定句柄窗口截图

            cDll.RECT rectSrc = new cDll.RECT();
            GetWindowRect(hWnd, ref rectSrc);
            int widthSrc = rectSrc.Right - rectSrc.Left; //窗口的宽度
            int heightSrc = rectSrc.Bottom - rectSrc.Top; //窗口的高度
            int xSrc = rectSrc.Left;
            int ySrc = rectSrc.Top;
            var imgSrc = Common.HandleImg.GetScreenImg(xSrc, ySrc, widthSrc, heightSrc);

            #endregion

            #region 普票判断

            var imgPP = Properties.Resources.PP;
            System.Drawing.Point zp = Common.HandleImg.FindPicFromImage(imgSrc, imgPP);
            var wtPP = imgPP.Width;
            var htPP = imgPP.Height;
            var imgPPCut = Common.HandleImg.GetScreenImg(rectSrc.Left + zp.X, rectSrc.Top + zp.Y, wtPP, htPP); //对样本位置截图
            double threshold = Common.HandleImg.MatchPicBySift(imgPP, imgPPCut);
            if (threshold < 0.9)
            {
                err = "这是普通发票，请使用普通发票填开！";
                return err;
            }

            #endregion

            Thread.Sleep(300);
            var imgImp = Properties.Resources.Invimport;
            System.Drawing.Point picFromSrc = Common.HandleImg.FindPicFromImage(imgSrc, imgImp); //导入
            var wtImp = imgImp.Width; //获取图片尺寸，计算中心点
            var htImp = imgImp.Height;
            var xOfsImp = wtImp / 2;
            var yOfsImp = htImp / 2;
            var clickSubx = rectSrc.Left + picFromSrc.X + xOfsImp; //加偏移量xOfsImp，尽量靠近中心点  35（固定偏移量）
            var clickSuby = rectSrc.Top + picFromSrc.Y + yOfsImp; //加偏移量yOfsImp，尽量靠近中心点   20（固定偏移量）
            cDllExt.mouseClick(clickSubx, clickSuby);

            Thread.Sleep(300);
            var imgSrc1 = Common.HandleImg.GetScreenImg(xSrc, ySrc, widthSrc, heightSrc); //手工导入
            var imgImMan = Properties.Resources.Invimport_Manual;
            System.Drawing.Point picFromSrc1 = Common.HandleImg.FindPicFromImage(imgSrc1, imgImMan);
            var wtImMan = imgImMan.Width;
            var htImMan = imgImMan.Height;
            var xOfsImpMan = wtImMan / 2;
            var yOfsImpMan = htImMan / 2;
            var clickSubx1 = rectSrc.Left + picFromSrc1.X + xOfsImpMan;
            var clickSuby1 = rectSrc.Top + picFromSrc1.Y + yOfsImpMan;
            cDllExt.mouseClick(clickSubx1, clickSuby1);

            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt() * 3);
            var imgSrc2 = Common.HandleImg.GetScreenImg(xSrc, ySrc, widthSrc, heightSrc); //导入xml
            var imgImXml = Properties.Resources.import_XML;
            System.Drawing.Point picFromSrc2 = Common.HandleImg.FindPicFromImage(imgSrc2, imgImXml);
            var wtImXml = imgImXml.Width;
            var htImXml = imgImXml.Height;
            var xOfsImpXml = wtImXml / 2;
            var yOfsImpXml = htImXml / 2;
            var clickSubx2 = rectSrc.Left + picFromSrc2.X + xOfsImpXml;
            var clickSuby2 = rectSrc.Top + picFromSrc2.Y + yOfsImpXml;
            cDllExt.mouseClick(clickSubx2, clickSuby2);

            #region 选择导入文件

            var ifindount = 0;
            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt());
            var openwin = new Model.WinProperty();
            var sname = new StringBuilder();
            sname.Append("文件对话框");
            openwin.hwnd = cDll.FindWindow(null, sname);
            while (openwin.hwnd.ToInt32() == 0 && ifindount < 10)
            {
                ifindount++;
                openwin.hwnd = cDll.FindWindow(null, sname);
                Thread.Sleep(300);
            }

            if (openwin.hwnd.ToInt32() == 0)
            {
                err = $"没有找到窗口[{sname}]或者系统运行速度太慢，请与系统管理员联系";
                return err;
            }

            cDllExt.GetWinProperty(openwin);
            var openmainOle = AutomationElement.FromHandle(openwin.hwnd);
            if (openmainOle == null)
            {
                err += "没有找到输入窗体";
                return err;
            }

            var condition0 = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit);
            var condition1 = new PropertyCondition(AutomationElement.NameProperty, "文件名(N):");
            var andcondition = new AndCondition(condition0, condition1);
            var eliemt = openmainOle.FindFirst(TreeScope.Descendants, andcondition);
            ifindount = 0;
            while (eliemt == null && ifindount < 5)
            {
                eliemt = openmainOle.FindFirst(TreeScope.Descendants, andcondition);
                ifindount++;
                if (eliemt == null)
                {
                    System.Threading.Thread.Sleep(500);
                }
            }

            var vt = (ValuePattern) eliemt.GetCurrentPattern(ValuePattern.Pattern);
            vt.SetValue(filePath);
            condition0 = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button);
            condition1 = new PropertyCondition(AutomationElement.NameProperty, "打开(O)");
            andcondition = new AndCondition(condition0, condition1);
            eliemt = openmainOle.FindFirst(TreeScope.Children, andcondition);
            if (eliemt == null)
            {
                eliemt = openmainOle.FindFirst(TreeScope.Children, condition1);
            }

            if (eliemt == null)
            {
                var itop = openwin.position.Top - 50 + 25;
                var ileft = openwin.position.Left - 213 + 40;
                cDll.SetCursorPos(ileft, itop);
                cDllExt.mouseDoubleClick(ileft, itop);
            }
            else
            {
                var rect = eliemt.Current.BoundingRectangle;
                var itop = (int) (rect.Top + rect.Height / 2);
                var ileft = (int) (rect.Left + rect.Width / 2);
                cDll.SetCursorPos(ileft, itop);
                cDllExt.mouseDoubleClick(ileft, itop);
            }

            #endregion

            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt() * 3);
            IntPtr hWnd3 = cDll.FindWindow(null, "新开票软件"); //获取新开票句柄
            cDll.SetForegroundWindow(hWnd3); //设置为活动窗口
            var imgSrcSel = Common.HandleImg.GetScreenImg(xSrc, ySrc, widthSrc, heightSrc); //选择
            double thresholdSel = 0;
            int icountSel = 0;
            do
            {
                var imgSel = Properties.Resources.selectBWNew;
                System.Drawing.Point picFromSrc3 = Common.HandleImg.FindPicFromImage(imgSrcSel, imgSel);
                var wtSel = imgSel.Width;
                var htSel = imgSel.Height;
                var xOfsSel = wtSel / 2;
                var yOfsSel = htSel / 2;
                var clickSubx3 = rectSrc.Left + picFromSrc3.X + xOfsSel;
                var clickSuby3 = rectSrc.Top + picFromSrc3.Y + yOfsSel;
                cDllExt.mouseClick(clickSubx3, clickSuby3);
                Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt());
                var imgSrcSel1 = Common.HandleImg.GetScreenImg(xSrc, ySrc, widthSrc, heightSrc);
                thresholdSel = Common.HandleImg.MatchPicBySift(imgSrcSel, imgSrcSel1);
                icountSel++;
            } while (thresholdSel == 1 && icountSel < 10);

            // var imgSrc3 = Common.HandleImg.GetScreenImg(xSrc, ySrc, widthSrc, heightSrc); //选择
            // var imgSel = Properties.Resources.selectBWNew;
            // System.Drawing.Point picFromSrc3 = Common.HandleImg.FindPicFromImage(imgSrc3, imgSel);
            // var wtSel = imgSel.Width;
            // var htSel = imgSel.Height;
            // var xOfsSel = wtSel / 2;
            // var yOfsSel = htSel / 2;
            // var clickSubx3 = rectSrc.Left + picFromSrc3.X + xOfsSel;
            // var clickSuby3 = rectSrc.Top + picFromSrc3.Y + yOfsSel;
            // cDllExt.mouseClick(clickSubx3, clickSuby3);


            #region 发票代码

            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt());
            int icount = 0;
            while ((fpdm.ObjToString().Length == 0 || fphm.ObjToString().Length == 0) && icount < 10)
            {
                //发票代码
                var imgfadm = Properties.Resources.fpdm_BW_No;
                var imgfpdm1 = Properties.Resources.fpdm1; //用文字部分进行样本定位，保证准确度
                System.Drawing.Point pointfpdm = Common.HandleImg.FindPicFromImage(imgSrc, imgfpdm1);
                var wtfpdm = imgfadm.Width;
                var htfpdm = imgfadm.Height;
                var fpdmx = rectSrc.Left + pointfpdm.X;
                var fpdmy = rectSrc.Top + pointfpdm.Y;
                var fpdmbmp = Common.HandleImg.GetScreenImg(fpdmx + 67, fpdmy + 5, wtfpdm, htfpdm);
                fpdmbmp = Common.HandleImg.PicProcess(fpdmbmp);
                fpdmbmp.Save("C:\\税控接口\\fpdm_BW.png");
                var ocrfpdm = Common.HandleImg.Reconize(OcrType.发票代码, fpdmbmp);
                var matchfpdm = System.Text.RegularExpressions.Regex.Match(ocrfpdm, "\\d{10,12}");
                fpdm = matchfpdm.Value;
                //发票号码
                var imgfphm = Properties.Resources.fphm;
                System.Drawing.Point pointfphm = Common.HandleImg.FindPicFromImage(imgSrc, imgfphm);
                var wtfphm = imgfphm.Width;
                var htfphm = imgfphm.Height;
                var fphmx = rectSrc.Left + pointfphm.X;
                var fphmy = rectSrc.Top + pointfphm.Y;
                var fphmbmp = Common.HandleImg.GetScreenImg(fphmx, fphmy, wtfphm, htfphm);
                fphmbmp = Common.HandleImg.PicProcess(fphmbmp);
                fphmbmp.Save("C:\\税控接口\\fphm_BW.png");
                var ocrfphm = Common.HandleImg.Reconize(OcrType.发票号码, fpdmbmp);
                var matchfphm = System.Text.RegularExpressions.Regex.Match(ocrfphm, "\\d{8}");
                fphm = matchfphm.Value;
                Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt());
                icount++;
            }

            #endregion

            return "";
        }
    }
}